from datetime import datetime
import json
import logging
import threading
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from doc_service.models import Report
from doc_service.views import centimeter_transformation_point
from reportservice.helpers import ApiResponse
from yida_app_service.xu_digital_sign_client import XmDigitalSignBaseClient
from .yida_config import YidaClient
from oss_service.views import bucket as yida_bucket
from oss_service.views import digital_bucket
report_form_uuid = "FORM-5E859C69D49F452694E420EF7A162B4371MF"
logger = logging.getLogger(__name__)
yida_client = YidaClient()
digital_sign_client = XmDigitalSignBaseClient()
    
@csrf_exempt
@require_http_methods(["POST"])
def sign_order_completed(request):
    data = json.loads(request.body)
    sign_order_no = data.get("orderNo")
    submitUserDingtalkId = data.get("submitUserDingtalkId")
    if not sign_order_no:
        return ApiResponse.error(message="未传递订单编号-orderNo")
    try:
        report = Report.objects.get(digital_sign_order_no=sign_order_no)
    except Report.DoesNotExist:
        return ApiResponse.error(message="未找到该报告")
    res = yida_client.get_form_data_by_search_field(
        form_uuid=report_form_uuid,
        userId=yida_client.admin_user_id,
        search_field={"textField_lp93kxup": report.report_code}
    )
    if not res:
        return ApiResponse.error(message="宜搭中未找这条数据")
    formInstId = res[0].form_instance_id
    signInformation = json.loads(res[0].form_data.get('textField_ltmlzgdv', "{}"))
    if submitUserDingtalkId in signInformation.get("participants_p_list", []):
        signInformation["participants_p_list"] = [id for id in signInformation["participants_p_list"] if id != submitUserDingtalkId]
        yida_client.update_form_data_by_id(
            form_uuid=report_form_uuid,
            userId=yida_client.admin_user_id,
            form_inst_id=formInstId,
            update_field={"textField_ltmlzgdv": json.dumps(signInformation)}
        )
    yida_client.update_form_data_by_field(
        "FORM-6ABF70417C36461B94DCF647572F84B67EAC",
        yida_client.admin_user_id,
        [
            {
              "type": "TEXT",
              "operator": "eq",
              "componentName": "TextField",
              "key": "textField_lrzglud2",
              "value": sign_order_no
            },
            {
              "type": "TEXT",
              "operator": "eq",
              "componentName": "TextField",
              "key": "textField_lrzglud3",
              "value": submitUserDingtalkId
            }
        ],
        {
            "dateField_lrz1dyq6": int(datetime.now().timestamp()) * 1000,
        }
    )
    if not data.get("totalSigner"):
        return ApiResponse.success(message="已确认签署")
    if data.get("totalSigner") == data.get("signedNum"):
        sign_file_path = data.get("outputFilePath")
        if sign_file_path:
            yida_bucket.copy_object(
                "xu-digital-sign", sign_file_path, report.report_path + '/signed.pdf')
            return ApiResponse.success(message="total success")
        else:
            return ApiResponse.fail(message="outputFilePath is required.")
    return ApiResponse.success(message="sign success")

@csrf_exempt
@require_http_methods(["GET"])
def view_signed_file(request):
    order_no = request.GET.get("order_no")
    result = digital_sign_client.view_signed_file(order_no)
    redirect_url = result.get("data")
    if redirect_url:
        return redirect(redirect_url)
    else:
        return ApiResponse.fail("未找到报告")
    

def get_user_id(id_str):
    if not id_str:
        return None
    '''截取用户id'''
    if "-" in id_str:
        return id_str.split("-")[-1]
    else:
        return id_str
    
@csrf_exempt
@require_http_methods(["POST"])
def create_digital_sign_order(request):
    datasource: dict[str, any] = json.loads(request.body)
    form_inst_ids:list = datasource.get("form_inst_ids")
    report_results = yida_client.get_form_items_by_id_list(report_form_uuid,form_inst_ids,yida_client.admin_user_id)
    threading.Thread(target=create_digital_sign_order_thread,args=(form_inst_ids, report_results,)).start()
    return ApiResponse.success(message="订单创建成功")

def create_digital_sign_order_thread(form_inst_ids:list, report_info:list):
    for index, report_result in enumerate(report_info):
        form_data = report_result.form_data
        report_code = form_data.get("textField_lp93kxup")
        model_uuid = form_data.get("textField_lqbsdaaj")
        report_model = yida_client.get_form_data_by_search_field(
            "FORM-D4C9AA2AA5634D7CB46142B94F6B8441IA1U", yida_client.admin_user_id, {"textField_lq966fhr": model_uuid})
        model_info = report_model[0].form_data
        app_history = yida_client.get_approve_history(form_inst_ids[index],yida_client.admin_user_id)
        jcr1_id = get_user_id(form_data.get("selectField_lpgut0ng_id")) # 检测人1
        jcr2_id = get_user_id(form_data.get("selectField_lqeidrd3_id")) # 检测人2
        shr = next((item for item in reversed(app_history) if item.show_name == "待审核"), None) # 审核人
        pzr_id = next((item for item in reversed(app_history) if item.show_name == "总工审核"), None).operator_user_id # 批准人
        tl_id = get_user_id(form_data.get("selectField_lqvpbi42_id")) # 组长 专家组
        tm1_id = get_user_id(form_data.get("selectField_lqvpbi43_id")) # 组员1
        tm2_id = get_user_id(form_data.get("selectField_lqvpbi45_id")) # 组员2
        sign_areas_p = model_info['tableField_ls9optr6'] # 获取个人签署坐标配置
        participants_personal = []
        participants_p = [jcr1_id,jcr2_id]
        if model_uuid not in ["WVC66WC1M98HSGFSA8D4Q8XVZZWG3CM2G3WQLP47","H7D667C1FNCH7N0O683XH6RP8WN6281IG3WQLR7"]:
            # 评估和鉴定不加审核批准人
            if shr:
                participants_p += [shr.operator_user_id]
            participants_p += [pzr_id]
        if tl_id:
            participants_p += [tl_id, tm1_id, tm2_id]
        for index_area, sign_area in enumerate(sign_areas_p):
            if len(participants_p) <= index_area:
                continue
        #个人章
            participants_personal.append({
                "userType": "2",
                "dingtalkUserId": participants_p[index_area],
                "coordinate": rf'[{{"lby":{centimeter_transformation_point(sign_area["numberField_ls9optra"])},"lbx":{centimeter_transformation_point(sign_area["numberField_ls9optr9"])},"rty":{centimeter_transformation_point(sign_area["numberField_ls9optra"]) + centimeter_transformation_point(sign_area["numberField_ls9optro"])},"rtx":{centimeter_transformation_point(sign_area["numberField_ls9optr9"]) + centimeter_transformation_point(sign_area["numberField_ls9optro"])},"page":{sign_area["numberField_ls9optr7"]}}}]'
            })
        official_seal_areas = model_info.get("tableField_lt8ndw9l")
        
        official_seal_area_list = []
        for official_seal_area in official_seal_areas:# 获取企业章坐标配置
            seal = json.loads(json.loads(official_seal_area.get("associationFormField_lvdgd8ot_id")))[0]
            matching_items = [item for item in official_seal_area_list if item.get("sealFileUuid") == seal.get("subTitle")]
            if matching_items:
                official_coordinate = matching_items[0].get("coordinate_list")
            else:
                official_seal_info = {
                    "userType": "2",
                    "dingtalkUserId": pzr_id,
                    "sealFileUuid": seal.get("subTitle"),
                    "coordinate":"",
                    "coordinate_list":[],
                    "enterpriseCardno":"93k12jadfas01231203",
                    "coordinateRiding":f"{centimeter_transformation_point(official_seal_area['numberField_ls9optrm'])}F,{centimeter_transformation_point(official_seal_area['numberField_lt8ndw9m'])}F" if official_seal_area.get("numberField_ls9optrm") else None
                    # "coordinateRiding":"200.0F, 350.0F"
                }
                official_seal_area_list.append(official_seal_info)
                official_coordinate = official_seal_info.get("coordinate_list")
            coordinate_item = {
                'lbx': centimeter_transformation_point(official_seal_area['numberField_lt8ndw9o']),
                'lby': centimeter_transformation_point(official_seal_area['numberField_lt8ndw9n']),
                'rtx': centimeter_transformation_point(official_seal_area['numberField_lt8ndw9o']) + centimeter_transformation_point(official_seal_area['numberField_lt8ndw9m']),
                'rty': centimeter_transformation_point(official_seal_area['numberField_lt8ndw9n']) + centimeter_transformation_point(official_seal_area['numberField_lt8ndw9m']),
                'page': official_seal_area['numberField_lt8ndw9p']
            }
            official_coordinate.append(coordinate_item)
        for seal_e in official_seal_area_list:
            seal_e["coordinate"] = json.dumps(seal_e["coordinate_list"])
        try:
            report = Report.objects.get(report_code=report_code)
        except Exception as err:
            raise Exception("未找到报告")
        data = {
            "participants": [],
            "callbackUrl":"https://api.zjcxjc.cn/api/v1/yida-app/chengxiang_2025/sign-order-completed"
        }
        data["participants"].extend(participants_personal)
        data["participants"].extend(official_seal_area_list)
        res = digital_sign_client.create_order(data)
        if (res["code"] == 200):
            digital_bucket.copy_object(
                "xu-bk-chengxiang", f"{report.report_path}/whole.pdf", res['data']['contractFilePath']+'origin.pdf')
            ds_no = res["data"]["orderNum"]
            print('-',ds_no)
            report.digital_sign_order_no = ds_no
            report.save()
            # 宜搭自动化通知签署
            notify_p = list(set(participants_p))
            # 更新签署状态json字段
            if form_data.get("textField_ltmlzgdv"):
                sign_status = json.loads(form_data.get("textField_ltmlzgdv"))
            else:
                sign_status = {}
            sign_status['orderNo'] = ds_no
            sign_status["participants_p_list"] = notify_p
            status_str = json.dumps(sign_status)
            yida_client.update_form_data_by_id(
                report_form_uuid,
                yida_client.admin_user_id,
                form_inst_ids[index],
                {
                    "textField_ltmlzgdv":status_str
                }
            )
            # 免验证签署人员
            no_verify_signer = [
                "024021201326222852",
                "4302516026430609",
                "1410641735697591",
                "032331201649699235",
                "0401131318699235"
            ]   
            for p_user_id in notify_p:
                if p_user_id in no_verify_signer:
                    try:
                        nv_result = digital_sign_client.sign_coordinate_pass_time(p_user_id,ds_no)
                    except Exception as err:
                        logger.error(err)
                    continue
                yida_client.create_form_data("FORM-6ABF70417C36461B94DCF647572F84B67EAC",
                                         yida_client.admin_user_id,
                                         {
                                              "textField_ls0gkw31": report_code,
                                              "textField_lrzglud2": ds_no,
                                              "textField_lrzglud3": p_user_id,
                                              "employeeField_ls0fsd2m": [p_user_id],
                                              "selectField_ls0fsd2n": "个人"
                                         })
        else:
            raise Exception("订单创建失败")